package com.jinandi.app.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jinandi.app.dao.AuthorityDao;
import com.jinandi.app.dao.RoleDao;
import com.jinandi.app.dao.UserDao;
import com.jinandi.app.domain.Authorit;
import com.jinandi.app.domain.Role;
import com.jinandi.app.domain.User;

@Service
public class RoleService extends BaseService{
	private RoleDao roleDao;

	private JdbcTemplate jdbcTemplate;
	
	private AuthorityDao authorityDao;

	@Autowired
	private UserDao userDao;//
	
	@Autowired
	public void setAuthorityDao(AuthorityDao authorityDao) {
		this.authorityDao = authorityDao;
	}
	
	@Autowired
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Autowired
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	/**
	 * <用户拥有的角色>
	 * @param id
	 * @return
	 * @author CGC 
	 * 创建日期:2013-5-9 下午1:48:46
	 */
	@Transactional
	public List<Map<String,Object>> findList(Long id) {
		return jdbcTemplate.queryForList("select a.id , a.auName, a.authority,(select u.id from jnd_user u , jnd_role r where u.id = ? and u.id = r.user_id and r.authorit_id = a.id ) as uid from jnd_authorit a", id);
	}

	/**
	 * <修改用户拥有的角色>
	 * @param uid
	 * @param ids
	 * @author CGC 
	 * 创建日期:2013-5-9 下午1:49:02
	 */
	@Transactional
	public void modifyRole(Long uid, String[] ids) {
		User user = userDao.findUserById(uid);
		roleDao.deleteRoleByUserId(uid);
		for (String id : ids) {
			Role role = new Role();
			Authorit authorit = authorityDao.findAuthoritById(Long.valueOf(id));
			role.setAuthorit(authorit);
			role.setAuthority(authorit.getAuthority());
			role.setUser(user);
			roleDao.save(role);
		}
	}
}
